package com.example.common.networkutil

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

class MyConverterFactory : Converter.Factory {

    private var gson: Gson? = null

    companion object {
        fun create(gson: Gson?) :MyConverterFactory{
            if (gson == null) {
                throw Throwable("gson is null")
            }
            return MyConverterFactory(gson)
        }
    }

    private constructor(gson: Gson) {
        this.gson = gson
    }

    override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit): Converter<*, RequestBody>? {
        val adapter = gson!!.getAdapter(TypeToken.get(type))
        //请求拦截器
        return MyRequestBodyConverter(gson!!, adapter)
    }

    override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
        val adapter = gson!!.getAdapter(TypeToken.get(type))
        //接收拦截器
        return MyResponseBodyConverter(adapter)
    }
}

